#include<QFileDialog>
#include<QMessageBox>
#include <QtCore/QTextStream>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include <sys\stat.h>
#include <iostream>
#include <string>
#include<assert.h>

#include "pt1_decoder.h"
#include "ui_pt1_decoder.h"

QString bmppath;
QString textpath;

PT1_decoder::PT1_decoder(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PT1_decoder)
{
    ui->setupUi(this);

    connect( ui->pushButton_browse_3, SIGNAL( clicked() ), this, SLOT( browse_3() ) );
    connect( ui->pushButton_browse_4, SIGNAL( clicked() ), this, SLOT( browse_4() ) );
    connect( ui->pushButton_decode, SIGNAL( clicked() ), this, SLOT( decode() ) );
}

PT1_decoder::~PT1_decoder()
{
    delete ui;
}

void PT1_decoder::browse_3()
{
    bmppath = QFileDialog::getOpenFileName(
        this,
        "Choose a file to open",
        QString::null,
        QString::null);

    ui->lineEdit_3->setText( bmppath );
}

void PT1_decoder::browse_4()
{
    textpath = QFileDialog::getOpenFileName(
        this,
        "Choose a file to open",
        QString::null,
        QString::null);

    ui->lineEdit_4->setText( textpath );
}

void PT1_decoder::decode()
{
    unsigned long pos=0;
    unsigned char *bmp_buf,*txt_buf,temp1,temp,temp2,i=0,t=1;
    bmp_buf=&temp;
    txt_buf=&temp1;

    char *textfile;
    textfile = textpath.toLatin1().data();
    char *bmpfile;
    bmpfile = bmppath.toLatin1().data();

    FILE *fpt=fopen(textfile,"w");
    FILE *fp=fopen(bmpfile,"rb+");

    while(i<4)
          {
           fseek(fp,i+10,SEEK_SET);
           fread(bmp_buf,1,1,fp);
           pos+=*bmp_buf*(pow(256,i));
           i++;
         }

          fseek(fp,pos,SEEK_SET);


          while(t!=0)
        {
         *txt_buf=0;
         t=0,i=0;
         while(i<8)
         {
           fread(bmp_buf,1,1,fp);
           *txt_buf=*bmp_buf&1;
           t+=*txt_buf<<i;
           i++;
         }
         *txt_buf=t;
         fwrite(txt_buf,1,1,fpt);
        }
          fclose(fpt);
          fclose(fp);

          ui->msg_2->setText("Decoding completed.");
}

void PT1_decoder::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
